package com.datamanage.asset.controller;

import com.datamanage.asset.dto.DatasetDTO;
import com.datamanage.asset.entity.Dataset;
import com.datamanage.asset.service.DatasetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/datasets")
public class DatasetController {
    
    @Autowired
    private DatasetService datasetService;
    
    @PostMapping
    public ResponseEntity<?> createDataset(@RequestBody DatasetDTO datasetDTO, 
                                         @RequestHeader("CompanyId") Long companyId,
                                         @RequestHeader("UserId") Long userId) {
        try {
            Dataset dataset = datasetService.createDataset(datasetDTO, userId, companyId);
            
            Map<String, Object> response = new HashMap<String, Object>();
            response.put("dataset", dataset);
            response.put("message", "数据集创建成功");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<String, Object>();
            response.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<?> getDatasetById(@PathVariable Long id, 
                                          @RequestHeader("CompanyId") Long companyId) {
        Optional<Dataset> dataset = datasetService.getDatasetById(id, companyId);
        if (dataset.isPresent()) {
            return ResponseEntity.ok(dataset.get());
        } else {
            return ResponseEntity.notFound().build();
        }
    }
    
    @GetMapping
    public ResponseEntity<?> getAllDatasets(@RequestHeader("CompanyId") Long companyId,
                                          @RequestParam(defaultValue = "0") int page,
                                          @RequestParam(defaultValue = "10") int size) {
        Pageable pageable = PageRequest.of(page, size);
        Page<Dataset> datasets = datasetService.getAllDatasets(companyId, pageable);
        return ResponseEntity.ok(datasets);
    }
    
    @GetMapping("/user/{userId}")
    public ResponseEntity<?> getDatasetsByUserId(@PathVariable Long userId,
                                               @RequestHeader("CompanyId") Long companyId,
                                               @RequestParam(defaultValue = "0") int page,
                                               @RequestParam(defaultValue = "10") int size) {
        Pageable pageable = PageRequest.of(page, size);
        Page<Dataset> datasets = datasetService.getDatasetsByUserId(userId, companyId, pageable);
        return ResponseEntity.ok(datasets);
    }
    
    @GetMapping("/type/{type}")
    public ResponseEntity<?> getDatasetsByType(@PathVariable String type,
                                             @RequestHeader("CompanyId") Long companyId,
                                             @RequestParam(defaultValue = "0") int page,
                                             @RequestParam(defaultValue = "10") int size) {
        Pageable pageable = PageRequest.of(page, size);
        Page<Dataset> datasets = datasetService.getDatasetsByType(type, companyId, pageable);
        return ResponseEntity.ok(datasets);
    }
    
    @PutMapping("/{id}")
    public ResponseEntity<?> updateDataset(@PathVariable Long id, 
                                         @RequestBody DatasetDTO datasetDTO,
                                         @RequestHeader("CompanyId") Long companyId,
                                         @RequestHeader("UserId") Long userId) {
        try {
            Dataset dataset = datasetService.updateDataset(id, datasetDTO, companyId);
            
            Map<String, Object> response = new HashMap<String, Object>();
            response.put("dataset", dataset);
            response.put("message", "数据集更新成功");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<String, Object>();
            response.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteDataset(@PathVariable Long id, 
                                         @RequestHeader("CompanyId") Long companyId,
                                         @RequestHeader("UserId") Long userId) {
        try {
            datasetService.deleteDataset(id, companyId);
            
            Map<String, Object> response = new HashMap<String, Object>();
            response.put("message", "数据集删除成功");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<String, Object>();
            response.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    @PostMapping("/{id}/analyze")
    public ResponseEntity<?> analyzeDataset(@PathVariable Long id, 
                                          @RequestHeader("CompanyId") Long companyId) {
        try {
            List<Dataset> analysisResult = datasetService.analyzeDataset(id, companyId);
            
            Map<String, Object> response = new HashMap<String, Object>();
            response.put("result", analysisResult);
            response.put("message", "数据分析完成");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<String, Object>();
            response.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
}